//
//  WBStatusListViewModel.swift
//  weiboswift
//
//  Created by dingzhibing on 2017/3/21.
//  Copyright © 2017年 dingzhibing. All rights reserved.
//

import Foundation

private let maxPullupTryTimes = 3
//微博数据列表数据模型
//父类的选择  如果类需要使用 kvc或者字典转模型框架设置对象值，就需要继承自 nsobject
//           如果类只需包装一些代码逻辑，就可以不用任何父类
class WBStatusListViewModel {
    
    //微博模型数组懒加载
    lazy var statusList = [WBStatus]()
    
    private var pullupErrorTimes = 0
    
    func loadStatus(pullup:Bool,completion:@escaping (_ isSuccess:Bool,_ shouldRefresh:Bool)->()){
        if pullup && pullupErrorTimes > maxPullupTryTimes {
            completion(true,false)
            return
        }
        
        //下拉刷新 since_id取出数组中第一条微博的id
        let sinceIdTemp = pullup ? 0 : (statusList.first?.id ?? 0)
        
        //上拉刷新
        let maxIdTemp = !pullup ? 0 : (statusList.last?.id ?? 0)
        print("maxIdTemp:\(maxIdTemp)");
        print("sinceIdTemp:\(sinceIdTemp)");
        WBNetworkManager.shared.statusList(sinceId: sinceIdTemp,maxId: maxIdTemp>0 ? maxIdTemp-1 : 0) { (list, isSuccess) in
            //字典转模型
            guard let array = NSArray.yy_modelArray(with: WBStatus.self, json: list ?? []) as? [WBStatus] else {
                
                completion(isSuccess,false)
                
                return
            }
            
            //拼接数据
            if pullup {
                self.statusList += array
            }else{
                //下拉刷新应该将数组拼接在前边
                self.statusList = array + self.statusList
            }

            if pullup && array.count == 0 {
                self.pullupErrorTimes += 1
                
                completion(isSuccess,false)
            }else{
                //完成回调
                completion(isSuccess,true)
            }
  
        }
    }
}
